//
//  CustomViewController.m
//  ZXingDemo
//
//  Created by zhangcheng on 13-3-27.
//  Copyright (c) 2013年 zhangcheng All rights reserved.
//

#import "CustomViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "GoodDetailViewController.h"
@interface CustomViewController ()
{
    UIImageView * _line;
    
    BOOL _isSelf;
}
@end

@implementation CustomViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _isSelf=YES;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self openPhoto];
        
        UIBarButtonItem *photoLibraryButton = [[UIBarButtonItem alloc] initWithTitle:@"相册选择" style:UIBarButtonItemStyleBordered target:self action:@selector(pressPhotoLibraryButton:)];
        self.navigationItem.rightBarButtonItem=photoLibraryButton;
        
        [self showUI];
        
    });
}

-(void)showUI{
    
    CGFloat barW=280;
    
    CGFloat w=(ScreenSize.width-barW)/2;
    
    CGFloat h=(ScreenSize.height-barW)/2.0;
    

    //最上部view
    
    UIView* upView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,ScreenSize.width, h)];
    
    upView.alpha = 1;
    
    upView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
    
    [self.view addSubview:upView];
    

    
    //左侧的view
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, h, w, barW)];
    
    leftView.alpha = 1;
    
    leftView.backgroundColor =[UIColor colorWithWhite:0 alpha:0.4];
    
    [self.view addSubview:leftView];

    
    //中间扫描框
    
    UIImageView * imgV=[[UIImageView alloc]initWithFrame:CGRectMake(w, h, barW, barW)];
    
    imgV.image=[UIImage imageNamed:@"zbarimg.png"];
    
    [self.view addSubview:imgV];
    
    //条形码 基准线
    UIView * barView=[[UIView alloc]initWithFrame:CGRectMake(imgV.frame.origin.x+10, imgV.frame.origin.y+imgV.frame.size.height/2.0, imgV.frame.size.width-20, 1)];
    
    barView.backgroundColor=[UIColor redColor];
    
    [self.view addSubview:barView];
    
    //右侧的view
    
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(ScreenSize.width-w, h, w, barW)];
    
    rightView.alpha = 1;
    
    rightView.backgroundColor =[UIColor colorWithWhite:0 alpha:0.4];
    
    [self.view addSubview:rightView];
    
 
    
    //底部view
    
    UIView * downView = [[UIView alloc] initWithFrame:CGRectMake(0, h+barW, ScreenSize.width, ScreenSize.height-h-barW)];
    
    downView.alpha = 1;
    
    downView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
    
    [self.view addSubview:downView];
    

    
    //用于说明的label
    
    UILabel * labIntroudction= [[UILabel alloc] init];
    
    labIntroudction.backgroundColor = [UIColor clearColor];
    
    labIntroudction.frame=CGRectMake(imgV.frame.origin.x, imgV.frame.origin.y+imgV.frame.size.height+5, barW, 30);
    
    labIntroudction.numberOfLines=0;
    
    labIntroudction.textColor=[UIColor whiteColor];
    
    labIntroudction.font=[UIFont systemFontOfSize:12];
    
    labIntroudction.text=@"将条形码置于矩形方框中心,距离屏幕15cm左右";
    
    labIntroudction.textAlignment=NSTextAlignmentCenter;
    
    [self.view addSubview:labIntroudction];
    

    
}


-(void)openPhoto{
    
    BOOL Custom= [UIImagePickerController
                  isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];//判断摄像头是否能用
    if (Custom) {
        [self initCapture];//启动摄像头
    }
    
}

- (void)pressPhotoLibraryButton:(UIButton *)button
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.allowsEditing = YES;
    picker.delegate = self;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:picker animated:YES completion:^{
        self.isScanning = NO;
        [self.captureSession stopRunning];
    }];
}

- (void)pressCancelButton:(UIButton *)button
{
    self.isScanning = NO;
    [self.captureSession stopRunning];
    if (_delegate && [_delegate respondsToSelector:@selector(customViewControllerDidCancel:)]) {
        [_delegate customViewControllerDidCancel:self];
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.isScanning=YES;
    [self.captureSession startRunning];
}
- (void)initCapture
{
    self.captureSession = [[AVCaptureSession alloc] init];
    
    AVCaptureDevice* inputDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    AVCaptureDeviceInput *captureInput = [AVCaptureDeviceInput deviceInputWithDevice:inputDevice error:nil];
    
    [self.captureSession addInput:captureInput];
    
    AVCaptureVideoDataOutput *captureOutput = [[AVCaptureVideoDataOutput alloc] init];
    
    captureOutput.alwaysDiscardsLateVideoFrames = YES;
    
    if (IOS7) {
        AVCaptureMetadataOutput*_output=[[AVCaptureMetadataOutput alloc]init];
        
        [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
        
        [self.captureSession setSessionPreset:AVCaptureSessionPreset640x480];
        
        [self.captureSession addOutput:_output];
        
        _output.metadataObjectTypes =@[AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypeQRCode];
        
        if (!self.captureVideoPreviewLayer) {
            self.captureVideoPreviewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
        }
        // NSLog(@"prev %p %@", self.prevLayer, self.prevLayer);
        self.captureVideoPreviewLayer.frame = self.view.bounds;
        self.captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        [self.view.layer addSublayer: self.captureVideoPreviewLayer];
        
        self.isScanning = YES;
        [self.captureSession startRunning];
        
        
    }else{
        
        [captureOutput setSampleBufferDelegate:self queue:dispatch_get_main_queue()];
        
        NSString* key = (NSString *)kCVPixelBufferPixelFormatTypeKey;
        
        NSNumber* value = [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA];
        
        NSDictionary *videoSettings = [NSDictionary dictionaryWithObject:value forKey:key];
        
        [captureOutput setVideoSettings:videoSettings];
        
        [self.captureSession addOutput:captureOutput];
        
        NSString* preset = 0;
        
        if (NSClassFromString(@"NSOrderedSet") && // Proxy for "is this iOS 5" ...
            [UIScreen mainScreen].scale > 1 &&
            [inputDevice
             supportsAVCaptureSessionPreset:AVCaptureSessionPresetiFrame960x540]) {
                // NSLog(@"960");
                preset = AVCaptureSessionPresetiFrame960x540;
            }
        
        if (!preset) {
            // NSLog(@"MED");
            preset = AVCaptureSessionPresetMedium;
        }
        self.captureSession.sessionPreset = preset;
        
        if (!self.captureVideoPreviewLayer) {
            self.captureVideoPreviewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
        }
        // NSLog(@"prev %p %@", self.prevLayer, self.prevLayer);
        self.captureVideoPreviewLayer.frame = self.view.bounds;
        
        self.captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        
        [self.view.layer addSublayer: self.captureVideoPreviewLayer];
        
        self.isScanning = YES;
        
        [self.captureSession startRunning];
    
    }
}

- (UIImage *) imageFromSampleBuffer:(CMSampleBufferRef) sampleBuffer
{
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    // Lock the base address of the pixel buffer
    CVPixelBufferLockBaseAddress(imageBuffer,0);
    
    // Get the number of bytes per row for the pixel buffer
    size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
    // Get the pixel buffer width and height
    size_t width = CVPixelBufferGetWidth(imageBuffer);
    size_t height = CVPixelBufferGetHeight(imageBuffer);
    
    // Create a device-dependent RGB color space
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    if (!colorSpace)
    {
        NSLog(@"CGColorSpaceCreateDeviceRGB failure");
        return nil;
    }
    
    // Get the base address of the pixel buffer
    void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer);
    // Get the data size for contiguous planes of the pixel buffer.
    size_t bufferSize = CVPixelBufferGetDataSize(imageBuffer);
    
    // Create a Quartz direct-access data provider that uses data we supply
    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, baseAddress, bufferSize,
                                                              NULL);
    // Create a bitmap image from data supplied by our data provider
    CGImageRef cgImage =
    CGImageCreate(width,
                  height,
                  8,
                  32,
                  bytesPerRow,
                  colorSpace,
                  kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Little,
                  provider,
                  NULL,
                  true,
                  kCGRenderingIntentDefault);
    CGDataProviderRelease(provider);
    CGColorSpaceRelease(colorSpace);
    
    // Create and return an image object representing the specified Quartz image
    UIImage *image = [UIImage imageWithCGImage:cgImage];
    
       
    return image;
}

- (void)decodeImage:(UIImage *)image
{//进行解码
    
     self.isScanning = NO;
    ZBarSymbol *symbol = nil;
    
    ZBarReaderController* read = [ZBarReaderController new];
    
    read.readerDelegate = self;
    
    CGImageRef cgImageRef = image.CGImage;
    
    for(symbol in [read scanImage:cgImageRef])break;
    
    NSLog(@"Zbar---%@",symbol.data);
    
    if (symbol!=nil) {
        
        GoodDetailViewController *good =[ [GoodDetailViewController alloc]init];
        //由navigationController推向我们要推向的view
        good.goodCode=symbol.data;
        good.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:good animated:YES];
        
        if (_delegate && [_delegate respondsToSelector:@selector(customViewController:didScanResult:)]) {
            
            [self.delegate customViewController:self didScanResult:symbol.data];
            [self.captureSession stopRunning];
            
        }
    }else{
        [self showInfo:@"未识别"];
    }
}

UILabel * _label;

-(void)showInfo:(NSString * )info{
    [[self infoLabel] setHidden:NO];
    [[self infoLabel] setText:info];
    [UIView animateWithDuration:2.0 animations:^{
        _label.alpha=0;
    } completion:^(BOOL finished) {
        if (finished) {
            [_label removeFromSuperview];
            _label = nil;
        }
    }];
}
-(UILabel *)infoLabel{
    if (!_label) {
        _label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 80, 40)];
        _label.center=CGPointMake(ScreenSize.width/2.0, ScreenSize.height/3.0);
        _label.backgroundColor=[UIColor colorWithWhite:0 alpha:0.68];
        _label.textColor=[UIColor whiteColor];
        _label.layer.masksToBounds=YES;
        _label.layer.cornerRadius=4;
        _label.textAlignment=NSTextAlignmentCenter;
        _label.font = [UIFont systemFontOfSize:16];
        _label.hidden=YES;
        [self.view addSubview:_label];
    }
    return _label;
}

#pragma mark - AVCaptureVideoDataOutputSampleBufferDelegate

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
{
    UIImage *image = [self imageFromSampleBuffer:sampleBuffer];

    [self decodeImage:image];
}
#pragma mark AVCaptureMetadataOutputObjectsDelegate//IOS7下触发
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    
    if (metadataObjects.count>0)
    {
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        
         NSLog(@"metadataObject.stringValue : %@",metadataObject.stringValue);
        
       
        GoodDetailViewController *good =[ [GoodDetailViewController alloc]init];
        //由navigationController推向我们要推向的view
        good.goodCode=metadataObject.stringValue;
        good.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:good animated:YES];

        
        
        [self.delegate customViewController:self didScanResult:metadataObject.stringValue];
        
        [self.captureSession stopRunning];
       
    }
   
}



#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    [self dismissViewControllerAnimated:YES completion:^{[self decodeImage:image];}];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:^{
        self.isScanning = YES;
        [self.captureSession startRunning];
    }];
}



#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
    self.isScanning = YES;
    [self.captureSession startRunning];
}

#pragma mark -

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
